'use client'

import React, { useState } from 'react'
import {
    Card,
    Button,
    Select,
    Space,
    Typography,
    Checkbox,
    Row,
    Col,
    Alert,
    Modal,
    Form,
    Input,
    message,
    Progress,
    List,
    Tag,
    Divider
} from 'antd'
import {
    FileTextOutlined,
    FileExcelOutlined,
    FilePdfOutlined,
    CloudDownloadOutlined,
    SettingOutlined
} from '@ant-design/icons'
import { Task, TaskResult } from '@/types/task'

const { Text } = Typography
const { Option } = Select

interface ResultExportProps {
    task: Task
    results: TaskResult[]
    onExport?: (config: ExportConfig) => Promise<void>
}

interface ExportConfig {
    format: 'json' | 'csv' | 'xlsx' | 'pdf' | 'xml'
    includeMetadata: boolean
    includeImages: boolean
    includeVisualization: boolean
    compressionLevel: number
    customFields: string[]
    fileName?: string
    description?: string
}

interface ExportFormat {
    key: string
    name: string
    description: string
    icon: React.ReactNode
    extensions: string[]
    supportsImages: boolean
    supportsMetadata: boolean
}

const exportFormats: ExportFormat[] = [
    {
        key: 'json',
        name: 'JSON',
        description: '结构化数据格式，适合程序处理',
        icon: <FileTextOutlined />,
        extensions: ['.json'],
        supportsImages: false,
        supportsMetadata: true
    },
    {
        key: 'csv',
        name: 'CSV',
        description: '表格数据格式，适合Excel打开',
        icon: <FileExcelOutlined />,
        extensions: ['.csv'],
        supportsImages: false,
        supportsMetadata: true
    },
    {
        key: 'xlsx',
        name: 'Excel',
        description: 'Excel工作簿格式，支持多个工作表',
        icon: <FileExcelOutlined />,
        extensions: ['.xlsx'],
        supportsImages: true,
        supportsMetadata: true
    },
    {
        key: 'pdf',
        name: 'PDF报告',
        description: '完整的分析报告，包含图像和结果',
        icon: <FilePdfOutlined />,
        extensions: ['.pdf'],
        supportsImages: true,
        supportsMetadata: true
    },
    {
        key: 'xml',
        name: 'XML',
        description: '标准化的医学数据交换格式',
        icon: <FileTextOutlined />,
        extensions: ['.xml'],
        supportsImages: false,
        supportsMetadata: true
    }
]

export const ResultExport: React.FC<ResultExportProps> = ({
    task,
    results,
    onExport
}) => {
    const [form] = Form.useForm()
    const [exportModalVisible, setExportModalVisible] = useState(false)
    const [selectedFormat, setSelectedFormat] = useState<ExportFormat>(exportFormats[0])
    const [exporting, setExporting] = useState(false)
    const [exportProgress, setExportProgress] = useState(0)

    const handleExportClick = () => {
        setExportModalVisible(true)
    }

    const handleFormatChange = (formatKey: string) => {
        const format = exportFormats.find(f => f.key === formatKey)
        if (format) {
            setSelectedFormat(format)
        }
    }

    const handleExport = async () => {
        try {
            const values = await form.validateFields()
            setExporting(true)
            setExportProgress(0)

            const config: ExportConfig = {
                format: selectedFormat.key as ExportConfig['format'],
                includeMetadata: values.includeMetadata ?? true,
                includeImages: values.includeImages ?? false,
                includeVisualization: values.includeVisualization ?? false,
                compressionLevel: values.compressionLevel ?? 5,
                customFields: values.customFields ?? [],
                fileName: values.fileName,
                description: values.description
            }

            // 模拟导出进度
            const progressInterval = setInterval(() => {
                setExportProgress(prev => {
                    if (prev >= 90) {
                        clearInterval(progressInterval)
                        return 90
                    }
                    return prev + Math.random() * 20
                })
            }, 200)

            if (onExport) {
                await onExport(config)
            } else {
                // 默认导出实现
                await simulateExport(config)
            }

            clearInterval(progressInterval)
            setExportProgress(100)

            setTimeout(() => {
                setExporting(false)
                setExportProgress(0)
                setExportModalVisible(false)
                message.success('导出完成')
            }, 500)

        } catch (error) {
            console.error('Export failed:', error)
            message.error('导出失败')
            setExporting(false)
            setExportProgress(0)
        }
    }

    const simulateExport = async (config: ExportConfig): Promise<void> => {
        // 模拟导出过程
        return new Promise((resolve) => {
            setTimeout(() => {
                // 创建模拟数据并下载
                const data = generateExportData(config)
                downloadFile(data, config.fileName || `task_results.${config.format}`, config.format)
                resolve()
            }, 2000)
        })
    }

    const generateExportData = (config: ExportConfig): string => {
        switch (config.format) {
            case 'json':
                return JSON.stringify({
                    task: {
                        id: task.id,
                        name: task.name,
                        type: task.type,
                        description: task.description
                    },
                    results: results.map(result => ({
                        id: result.id,
                        status: result.status,
                        executionTime: result.executionTime,
                        data: result.data,
                        metrics: config.includeMetadata ? result.metrics : undefined
                    })),
                    exportConfig: config,
                    exportTime: new Date().toISOString()
                }, null, 2)

            case 'csv':
                const headers = ['ID', '状态', '执行时间', '结果类型']
                const rows = results.map(result => [
                    result.id,
                    result.status,
                    result.executionTime,
                    task.type
                ])
                return [headers.join(','), ...rows.map(row => row.join(','))].join('\n')

            case 'xml':
                return `<?xml version="1.0" encoding="UTF-8"?>
<TaskResults>
    <Task id="${task.id}" name="${task.name}" type="${task.type}">
        <Description>${task.description}</Description>
    </Task>
    <Results>
        ${results.map(result => `
        <Result id="${result.id}" status="${result.status}" executionTime="${result.executionTime}">
            ${result.data ? '<Data>...</Data>' : ''}
        </Result>`).join('')}
    </Results>
    <ExportInfo>
        <ExportTime>${new Date().toISOString()}</ExportTime>
        <Format>${config.format}</Format>
    </ExportInfo>
</TaskResults>`

            default:
                return JSON.stringify({ task, results, config }, null, 2)
        }
    }

    const downloadFile = (content: string, fileName: string, format: string) => {
        const mimeTypes: Record<string, string> = {
            json: 'application/json',
            csv: 'text/csv',
            xml: 'application/xml',
            txt: 'text/plain'
        }

        const blob = new Blob([content], { type: mimeTypes[format] || 'text/plain' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
    }

    const getResultSummary = () => {
        const totalResults = results.length
        const successResults = results.filter(r => r.status === 'success').length
        const errorResults = results.filter(r => r.status === 'error').length

        return { totalResults, successResults, errorResults }
    }

    const { totalResults, successResults, errorResults } = getResultSummary()

    return (
        <Card
            title={
                <Space>
                    <CloudDownloadOutlined />
                    <span>结果导出</span>
                </Space>
            }
        >
            <Space direction="vertical" size="large" className="w-full">
                {/* 导出概览 */}
                <Alert
                    message="导出信息"
                    description={
                        <Space direction="vertical" size="small">
                            <Text>任务: {task.name} ({task.type})</Text>
                            <Text>结果数量: {totalResults} (成功: {successResults}, 失败: {errorResults})</Text>
                            <Text>创建时间: {new Date(task.createdAt).toLocaleString()}</Text>
                        </Space>
                    }
                    type="info"
                    showIcon
                />

                {/* 快速导出按钮 */}
                <Row gutter={[16, 16]}>
                    <Col span={6}>
                        <Button
                            block
                            icon={<FileTextOutlined />}
                            onClick={() => {
                                setSelectedFormat(exportFormats[0])
                                handleExportClick()
                            }}
                        >
                            JSON格式
                        </Button>
                    </Col>
                    <Col span={6}>
                        <Button
                            block
                            icon={<FileExcelOutlined />}
                            onClick={() => {
                                setSelectedFormat(exportFormats[1])
                                handleExportClick()
                            }}
                        >
                            CSV格式
                        </Button>
                    </Col>
                    <Col span={6}>
                        <Button
                            block
                            icon={<FilePdfOutlined />}
                            onClick={() => {
                                setSelectedFormat(exportFormats[3])
                                handleExportClick()
                            }}
                        >
                            PDF报告
                        </Button>
                    </Col>
                    <Col span={6}>
                        <Button
                            block
                            type="primary"
                            icon={<SettingOutlined />}
                            onClick={handleExportClick}
                        >
                            自定义导出
                        </Button>
                    </Col>
                </Row>

                {/* 支持的格式列表 */}
                <Card size="small" title="支持的导出格式">
                    <List
                        size="small"
                        dataSource={exportFormats}
                        renderItem={(format) => (
                            <List.Item>
                                <List.Item.Meta
                                    avatar={format.icon}
                                    title={
                                        <Space>
                                            <span>{format.name}</span>
                                            <Text type="secondary">
                                                {format.extensions.join(', ')}
                                            </Text>
                                        </Space>
                                    }
                                    description={format.description}
                                />
                                <Space>
                                    {format.supportsImages && <Tag color="blue">支持图像</Tag>}
                                    {format.supportsMetadata && <Tag color="green">支持元数据</Tag>}
                                </Space>
                            </List.Item>
                        )}
                    />
                </Card>
            </Space>

            {/* 导出配置对话框 */}
            <Modal
                title="导出配置"
                open={exportModalVisible}
                onOk={handleExport}
                onCancel={() => setExportModalVisible(false)}
                okText="开始导出"
                cancelText="取消"
                width={600}
                confirmLoading={exporting}
                okButtonProps={{ disabled: exporting }}
            >
                {exporting && (
                    <div className="mb-4">
                        <Text>正在导出...</Text>
                        <Progress percent={Math.round(exportProgress)} />
                    </div>
                )}

                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        includeMetadata: true,
                        includeImages: false,
                        includeVisualization: false,
                        compressionLevel: 5,
                        fileName: `${task.name}_results_${new Date().toISOString().split('T')[0]}`
                    }}
                >
                    <Form.Item
                        label="导出格式"
                        name="format"
                        initialValue={selectedFormat.key}
                    >
                        <Select onChange={handleFormatChange}>
                            {exportFormats.map(format => (
                                <Option key={format.key} value={format.key}>
                                    <Space>
                                        {format.icon}
                                        <span>{format.name}</span>
                                    </Space>
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="文件名"
                        name="fileName"
                        rules={[{ required: true, message: '请输入文件名' }]}
                    >
                        <Input
                            placeholder="输入导出文件名"
                            suffix={selectedFormat.extensions[0]}
                        />
                    </Form.Item>

                    <Form.Item
                        label="描述"
                        name="description"
                    >
                        <Input.TextArea
                            placeholder="可选：添加导出描述"
                            rows={2}
                        />
                    </Form.Item>

                    <Divider>导出选项</Divider>

                    <Form.Item name="includeMetadata" valuePropName="checked">
                        <Checkbox disabled={!selectedFormat.supportsMetadata}>
                            包含元数据和性能指标
                        </Checkbox>
                    </Form.Item>

                    <Form.Item name="includeImages" valuePropName="checked">
                        <Checkbox disabled={!selectedFormat.supportsImages}>
                            包含原始图像数据
                        </Checkbox>
                    </Form.Item>

                    <Form.Item name="includeVisualization" valuePropName="checked">
                        <Checkbox disabled={!selectedFormat.supportsImages}>
                            包含结果可视化图像
                        </Checkbox>
                    </Form.Item>

                    {selectedFormat.key === 'pdf' && (
                        <Alert
                            message="PDF报告将包含完整的分析结果、图像和统计信息"
                            type="info"
                            showIcon
                            className="mb-4"
                        />
                    )}

                    {(selectedFormat.key === 'xlsx' || selectedFormat.key === 'pdf') && (
                        <Form.Item
                            label="压缩级别"
                            name="compressionLevel"
                        >
                            <Select>
                                <Option value={1}>最小压缩 (最快)</Option>
                                <Option value={5}>标准压缩</Option>
                                <Option value={9}>最大压缩 (最小文件)</Option>
                            </Select>
                        </Form.Item>
                    )}
                </Form>
            </Modal>
        </Card>
    )
}

export default ResultExport